// ==================== 审计追踪系统主窗口实现文件 ====================
// 文件功能：实现主窗口界面和核心业务逻辑
// 包含功能：三级权限管理、高级数据导出、插件系统集成
// 作者：审计追踪系统开发团队
// 版本：1.0.0

#include "mainwindow.h"
#include "usermanagementwidget.h"
#include "audittrailmodel.h"
#include "loginwidget.h"
#include "digitalsignature.h"
#include "permissionmanager.h"
#include "dataexporter.h"
#include "pluginsystem.h"

#include <QAction>
#include <QApplication>
#include <QTimer>
#include <QFileDialog>
#include <QMessageBox>
#include <QStandardItemModel>
#include <QJsonDocument>
#include <QJsonArray>
#include <QDateTime>
#include <QTableWidget>
#include <QHeaderView>
#include <QDir>

// ==================== 类型别名定义 ====================
// 简化代码，提高可读性
using AuditRecord = AuditLogger::AuditRecord;    // 审计记录类型别名
using ActionType = AuditLogger::ActionType;      // 操作类型别名

/**
 * @brief 将审计操作类型转换为字符串
 * @param action 操作类型枚举
 * @return 操作类型的字符串表示
 */
QString MainWindow::auditActionToString(AuditLogger::ActionType action)
{
    using Action = AuditLogger::ActionType;
    switch (action)
    {
    case Action::System:    return "System";   // 系统操作
    case Action::Create:    return "Create";   // 创建操作
    case Action::Read:      return "Read";     // 读取操作
    case Action::Update:    return "Update";   // 更新操作
    case Action::Delete:    return "Delete";   // 删除操作
    case Action::Login:     return "Login";    // 登录操作
    case Action::Logout:    return "Logout";   // 登出操作
    default:                return "Unknown";  // 未知操作
    }
}

/**
 * @brief 主窗口构造函数
 * 初始化所有核心组件和增强功能模块
 * @param parent 父窗口指针
 */
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_auditLogger(new AuditLogger(this))          // 审计日志记录器
    , m_userSession(new UserSession(this))          // 用户会话管理器
    , m_dbHandler(new DatabaseHandler(this))        // 数据库处理器
    , ui(new Ui::MainWindow)                        // UI界面
    , m_proxyModel(new QSortFilterProxyModel(this)) // 数据模型代理
    , m_userManagementWidget(nullptr)               // 用户管理界面
{
    // ==================== 基础UI初始化 ====================
    ui->setupUi(this);  // 设置UI界面

    // 注册元类型，用于信号槽传递
    qRegisterMetaType<AuditLogger::ActionType>("AuditLogger::ActionType");
    
    // 初始化界面和连接
    initUI();
    setupConnections();

    // ==================== 增强功能组件初始化 ====================
    m_permissionManager = new PermissionManager(this);  // 三级权限管理系统
    m_dataExporter = new DataExporter(this);            // 高级数据导出系统
    m_pluginSystem = new PluginSystem(this);            // 插件系统架构
    
    // ==================== 延迟初始化用户管理界面 ====================
    // 使用定时器延迟创建，确保主界面完全初始化后再创建子界面
    QTimer::singleShot(0, this, [this]() {
        m_userManagementWidget = new UserManagementWidget(m_dbHandler, this);
        m_userManagementWidget->setWindowFlags(Qt::Window);
    });
}

MainWindow::~MainWindow()
{
}

/**
 * @brief 初始化系统核心组件
 * 按顺序初始化数据库、审计系统、用户认证等核心功能
 * @return 初始化是否成功
 */
bool MainWindow::initializeSystem()
{
    // ==================== 第一步：初始化审计数据库 ====================
    QString dbPath = QCoreApplication::applicationDirPath() + "/audit_trail.db";
    QString dbPassword = "secure_password_123";  // 生产环境中应从配置文件读取
    
    if (!m_auditLogger->initialize(dbPath, dbPassword))
    {
        QMessageBox::critical(this, tr("系统错误"), tr("审计数据库初始化失败"));
        return false;
    }

    // ==================== 第二步：建立数据库连接 ====================
    if (!m_dbHandler->isConnected())
    {
        QMessageBox::critical(this, tr("系统错误"), tr("数据库连接失败"));
        return false;
    }

    // ==================== 第三步：初始化数据库架构 ====================
    // 使用审计系统的配置初始化数据库架构和权限表
    if (!m_dbHandler->initialize(m_auditLogger->getDatabasePath(), m_auditLogger->getEncryptionPassword()))
    {
        QMessageBox::critical(this, tr("系统错误"), tr("数据库架构初始化失败"));
        return false;
    }

    // ==================== 第四步：用户身份验证 ====================
    LoginWidget *login = new LoginWidget(m_userSession, this);
    login->exec();

    // 检查用户是否成功登录
    if (!m_userSession->isLoggedIn())
    {
        return false;  // 用户取消登录或认证失败
    }

    // ==================== 第五步：延迟初始化UI组件 ====================
    // 使用定时器确保UI完全初始化后再设置数据模型
    QTimer::singleShot(100, this, [this]() {
        // 记录用户登录事件到审计日志
        AuditLogger::AuditRecord loginRecord;
        loginRecord.timestamp = QDateTime::currentDateTime();
        loginRecord.userId = m_userSession->getCurrentUser();
        loginRecord.action = AuditLogger::ActionType::Login;
        loginRecord.description = tr("用户成功登录系统");
        m_auditLogger->logEvent(loginRecord);

        // 初始化审计日志数据模型
        AuditTrailModel *model = new AuditTrailModel(m_auditLogger, this);
        m_proxyModel->setSourceModel(model);
        auditLogTableView->setModel(m_proxyModel);
        auditLogTableView->setSortingEnabled(true);

        // 初始化信号连接
        initConnections();
    });

    return true;  // 系统初始化成功
}

void MainWindow::initUI()
{
    // 创建用户管理菜单
    QMenu *adminMenu = menuBar()->addMenu(tr("&Admin"));
    QAction *userManagementAction = adminMenu->addAction(tr("&User Management"));
    QAction *permissionManagementAction = adminMenu->addAction(tr("&Permission Management"));
    QAction *pluginManagerAction = adminMenu->addAction(tr("&Plugin Manager"));
    
    connect(userManagementAction, &QAction::triggered, this, &MainWindow::showUserManagement);
    connect(permissionManagementAction, &QAction::triggered, this, &MainWindow::showPermissionManagement);
    connect(pluginManagerAction, &QAction::triggered, this, &MainWindow::showPluginManager);
    
    // 创建导出菜单
    QMenu *exportMenu = menuBar()->addMenu(tr("&Export"));
    QAction *advancedExportAction = exportMenu->addAction(tr("&Advanced Export"));
    connect(advancedExportAction, &QAction::triggered, this, &MainWindow::showExportDialog);

    // 创建主窗口控件
    QWidget *centralWidget = new QWidget(this);
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);

    // 创建工具栏
    QHBoxLayout *toolbarLayout = new QHBoxLayout();

    refreshButton = new QPushButton(tr("Refresh"), this);
    exportButton = new QPushButton(tr("Export"), this);
    filterButton = new QPushButton(tr("Filter"), this);
    logoutButton = new QPushButton(tr("Logout"), this);

    toolbarLayout->addWidget(refreshButton);
    toolbarLayout->addWidget(exportButton);
    toolbarLayout->addWidget(filterButton);
    toolbarLayout->addStretch();
    toolbarLayout->addWidget(logoutButton);

    // 创建数值修改控件
    QHBoxLayout *valueLayout = new QHBoxLayout();
    QLabel *valueLabel = new QLabel(tr("Value:"), this);
    m_valueEdit = new QLineEdit(this);
    m_valueEdit->setPlaceholderText(tr("Enter value to modify"));
    QPushButton *modifyButton = new QPushButton(tr("Modify"), this);

    valueLayout->addWidget(valueLabel);
    valueLayout->addWidget(m_valueEdit);
    valueLayout->addWidget(modifyButton);

    // 连接修改按钮的点击事件
    connect(modifyButton, &QPushButton::clicked, this, &MainWindow::onModifyValue);

    // 创建过滤器控件
    QHBoxLayout *filterLayout = new QHBoxLayout();

    dateFromEdit = new QDateEdit(QDate::currentDate(), this);
    dateToEdit = new QDateEdit(QDate::currentDate(), this);
    userFilterEdit = new QLineEdit(this);
    actionComboBox = new QComboBox(this);

    filterLayout->addWidget(new QLabel(tr("From:"), this));
    filterLayout->addWidget(dateFromEdit);
    filterLayout->addWidget(new QLabel(tr("To:"), this));
    filterLayout->addWidget(dateToEdit);
    filterLayout->addWidget(new QLabel(tr("User:"), this));
    filterLayout->addWidget(userFilterEdit);
    filterLayout->addWidget(new QLabel(tr("Action:"), this));
    filterLayout->addWidget(actionComboBox);

    // 初始化操作类型过滤器
    actionComboBox->addItem(tr("All"), QVariant::fromValue(AuditLogger::ActionType::System));
    actionComboBox->addItem(tr("Create"), QVariant::fromValue(AuditLogger::ActionType::Create));
    actionComboBox->addItem(tr("Read"), QVariant::fromValue(AuditLogger::ActionType::Read));
    actionComboBox->addItem(tr("Update"), QVariant::fromValue(AuditLogger::ActionType::Update));
    actionComboBox->addItem(tr("Delete"), QVariant::fromValue(AuditLogger::ActionType::Delete));
    actionComboBox->addItem(tr("Login"), QVariant::fromValue(AuditLogger::ActionType::Login));
    actionComboBox->addItem(tr("Logout"), QVariant::fromValue(AuditLogger::ActionType::Logout));

    // 创建审计日志表格
    auditLogTableView = new QTableView(this);
    auditLogTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    auditLogTableView->setSelectionMode(QAbstractItemView::SingleSelection);
    auditLogTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    auditLogTableView->horizontalHeader()->setStretchLastSection(true);

    // 组装主布局
    mainLayout->addLayout(toolbarLayout);
    mainLayout->addLayout(valueLayout);
    mainLayout->addLayout(filterLayout);
    mainLayout->addWidget(auditLogTableView);

    setCentralWidget(centralWidget);
}

void MainWindow::onModifyValue()
{
    QString newValue = m_valueEdit->text();
    if (newValue.isEmpty())
    {
        QMessageBox::warning(this, tr("Warning"), tr("Please enter a value to modify"));
        return;
    }

    // 获取旧值（这里简化处理，实际应用中应该从数据源获取）
    QString oldValue = "previous_value";

    // 弹出验证对话框
    DigitalSignature dialog(m_userSession->getCurrentUser(), tr("Modify Value"), this);
    if (dialog.exec() == QDialog::Accepted)
    {
        // 记录审计日志
        AuditLogger::AuditRecord record;
        record.timestamp = QDateTime::currentDateTime();
        record.userId = m_userSession->getCurrentUser();
        record.action = AuditLogger::ActionType::Update;
        record.oldValue = oldValue; // 记录旧值
        record.newValue = newValue; // 记录新值
        record.description = tr("Modified value from %1 to %2").arg(oldValue).arg(newValue);
        m_auditLogger->logEvent(record);

        // 更新界面显示
        m_valueEdit->clear();
        refreshAuditLog();
    }
}

void MainWindow::onUserLogin(const QString &userId)
{
    Q_UNUSED(userId);
    setWindowTitle(tr("Audit Trail System - User: %1").arg(m_userSession->getCurrentUser()));
    refreshAuditLog();
}

void MainWindow::onUserLogout()
{
    // 记录登出事件
    AuditLogger::AuditRecord record;
    record.timestamp = QDateTime::currentDateTime();
     record.userId = m_userSession->getCurrentUser();
    record.action = AuditLogger::ActionType::Logout;
    record.description = tr("User logged out");
    m_auditLogger->logEvent(record);

    close();
}

void MainWindow::refreshAuditLog()
{
    QAbstractItemModel *model = auditLogTableView->model();
    if (model)
    {
        AuditTrailModel *auditModel = qobject_cast<AuditTrailModel *>(m_proxyModel->sourceModel());
        if (auditModel) {
            auditModel->refresh();
        }
    }
}

void MainWindow::exportAuditLog()
{
    if (!verifyElectronicSignature("EXPORT_AUDIT_LOG"))
    {
        QMessageBox::warning(this, tr("Warning"), tr("Electronic signature verification failed"));
        return;
    }

    QString fileName = QFileDialog::getSaveFileName(this, tr("Export Audit Log"),
                                                    QDir::homePath(),
                                                    tr("JSON Files (*.json);;CSV Files (*.csv)"));

    if (fileName.isEmpty())
    {
        return;
    }

    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QMessageBox::critical(this, tr("Error"), tr("Failed to open file for writing"));
        return;
    }

    QVector<AuditLogger::AuditRecord> records = m_auditLogger->queryEvents();

    if (fileName.endsWith(".json"))
    {
        QJsonArray jsonArray;
        for (const AuditRecord &record : records)
        {
            QJsonObject jsonObj;
            jsonObj["timestamp"] = record.timestamp.toString(Qt::ISODate);
            jsonObj["user_id"] = record.userId;
            jsonObj["action"] = this->auditActionToString(record.action);
            jsonObj["table_name"] = record.tableName;
            jsonObj["record_id"] = record.recordId;
            jsonObj["old_value"] = record.oldValue;
            jsonObj["new_value"] = record.newValue;
            jsonObj["description"] = record.description;
            jsonArray.append(jsonObj);
        }

        QJsonDocument doc(jsonArray);
        file.write(doc.toJson());
    }
    else if (fileName.endsWith(".csv"))
    {
        QTextStream stream(&file);
        stream << "Timestamp,User ID,Action,Table Name,Record ID,Old Value,New Value,Description\n";
        for (const AuditRecord &record : records)
        {
            stream << record.timestamp.toString(Qt::ISODate) << ","
                   << record.userId << ","
                   << this->auditActionToString(record.action) << ","
                   << record.tableName << ","
                   << record.recordId << ","
                   << record.oldValue << ","
                   << record.newValue << ","
                   << record.description << "\n";
        }
    }

    file.close();

    // 记录导出事件
    AuditRecord record;
    record.timestamp = QDateTime::currentDateTime();
     record.userId = m_userSession->getCurrentUser();
    record.action = AuditLogger::ActionType::System;
    record.description = tr("Exported audit log to %1").arg(fileName);
    m_auditLogger->logEvent(record);

    QMessageBox::information(this, tr("Success"), tr("Audit log exported successfully"));
}

void MainWindow::applyFilter()
{
    QDateTime from = QDateTime(dateFromEdit->date(), QTime(0, 0));
    QDateTime to = QDateTime(dateToEdit->date(), QTime(23, 59, 59));
    QString userId = userFilterEdit->text();
    AuditLogger::ActionType action = actionComboBox->currentData().value<AuditLogger::ActionType>();

    QVector<AuditRecord> records = m_auditLogger->queryEvents(userId, from, to, action);
    AuditTrailModel *auditModel = qobject_cast<AuditTrailModel *>(m_proxyModel->sourceModel());
    if (auditModel) {
        auditModel->setAuditRecords(records);
    }

    // 记录查询事件
    AuditRecord record;
    record.timestamp = QDateTime::currentDateTime();
     record.userId = m_userSession->getCurrentUser();
    record.action = AuditLogger::ActionType::Read;
    record.description = tr("Queried audit log with filters");
    m_auditLogger->logEvent(record);
}

bool MainWindow::verifyElectronicSignature(const QString &action)
{
     DigitalSignature dialog(m_userSession->getCurrentUser(), action, this);
    if (dialog.exec() == QDialog::Accepted)
    {
        // 记录电子签名事件
        AuditRecord record;
        record.timestamp = QDateTime::currentDateTime();
         record.userId = m_userSession->getCurrentUser();
        record.action = AuditLogger::ActionType::System;
        record.description = tr("Electronic signature verified for action: %1").arg(action);
        m_auditLogger->logEvent(record);
        return true;
    }
    return false;
}

void MainWindow::initConnections()
{
    // Connect UI actions
    if (ui->actionExit) {
        connect(ui->actionExit, &QAction::triggered, qApp, &QApplication::quit);
    }
    if (ui->actionAbout) {
        connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::showAboutDialog);
    }

    // Connect user session signals
     connect(m_userSession, SIGNAL(loginStatusChanged(bool)), this, SLOT(onUserLogin(QString)));
     connect(m_userSession, SIGNAL(loginStatusChanged(bool)), this, SLOT(onUserLogout()));

    // Connect database handler signals
     connect(m_dbHandler, SIGNAL(databaseError(QString)), this, SLOT(handleDatabaseError(QString)));

    // Connect toolbar buttons
    connect(refreshButton, &QPushButton::clicked, this, &MainWindow::refreshAuditLog);
    connect(exportButton, &QPushButton::clicked, this, &MainWindow::exportAuditLog);
    connect(filterButton, &QPushButton::clicked, this, &MainWindow::applyFilter);
     connect(logoutButton, &QPushButton::clicked, m_userSession, &UserSession::logoutUser);
}

void MainWindow::setupConnections()
{
    // 保留setupConnections方法，但将内容移到initConnections
    initConnections();
}

void MainWindow::handleDatabaseError(const QString &error)
{
    QMessageBox::critical(this, tr("Database Error"),
                          tr("A database error occurred: %1").arg(error),
                          QMessageBox::Ok);
    m_auditLogger->logAction(AuditLogger::ActionType::System, error);
}

void MainWindow::showUserManagement()
{
    if (!checkUserPermission(PERM_USER_MANAGE))
    {
        QMessageBox::warning(this, tr("Permission Denied"),
                             tr("You don't have permission to manage users."));
        return;
    }

    if (m_userManagementWidget) {
        m_userManagementWidget->refreshUserList();
        m_userManagementWidget->show();
        m_userManagementWidget->raise();
        m_userManagementWidget->activateWindow();
    }
}

void MainWindow::showAboutDialog()
{
    QMessageBox::about(this, tr("关于审计追踪系统"),
                       tr("<h2>审计追踪系统 v1.0.0</h2>"
                          "<p><b>功能特性：</b></p>"
                          "<ul>"
                          "<li>✅ 三级权限管理系统</li>"
                          "<li>✅ 高级数据导出功能</li>"
                          "<li>✅ 插件系统架构</li>"
                          "<li>✅ 数据库加密支持</li>"
                          "<li>✅ 电子签名验证</li>"
                          "</ul>"
                          "<p>版权所有 © 2023 审计追踪系统开发团队</p>"));
}

void MainWindow::showPermissionManagement()
{
    if (!checkUserPermission(PERM_USER_MANAGE)) {
        QMessageBox::warning(this, tr("Permission Denied"),
                           tr("You don't have permission to manage permissions."));
        return;
    }
    
    // Create and show permission management dialog
    QDialog *permissionDialog = new QDialog(this);
    permissionDialog->setWindowTitle(tr("Permission Management"));
    permissionDialog->setModal(true);
    permissionDialog->resize(800, 600);
    
    QVBoxLayout *layout = new QVBoxLayout(permissionDialog);
    
    // User selection
    QHBoxLayout *userLayout = new QHBoxLayout();
    QLabel *userLabel = new QLabel(tr("Select User:"), permissionDialog);
    QComboBox *userCombo = new QComboBox(permissionDialog);
    userCombo->addItems(QStringList() << "admin" << "user" << "operator");
    userLayout->addWidget(userLabel);
    userLayout->addWidget(userCombo);
    layout->addLayout(userLayout);
    
    // Permission level selection
    QHBoxLayout *levelLayout = new QHBoxLayout();
    QLabel *levelLabel = new QLabel(tr("Permission Level:"), permissionDialog);
    QComboBox *levelCombo = new QComboBox(permissionDialog);
     levelCombo->addItem(tr("Viewer (Level 1)"), static_cast<int>(USER_ROLE_VIEWER));
     levelCombo->addItem(tr("Operator (Level 2)"), static_cast<int>(USER_ROLE_OPERATOR));
     levelCombo->addItem(tr("Admin (Level 3)"), static_cast<int>(USER_ROLE_ADMIN));
    levelLayout->addWidget(levelLabel);
    levelLayout->addWidget(levelCombo);
    layout->addLayout(levelLayout);
    
    // Buttons
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *applyButton = new QPushButton(tr("Apply"), permissionDialog);
    QPushButton *closeButton = new QPushButton(tr("Close"), permissionDialog);
    buttonLayout->addStretch();
    buttonLayout->addWidget(applyButton);
    buttonLayout->addWidget(closeButton);
    layout->addLayout(buttonLayout);
    
    connect(applyButton, &QPushButton::clicked, [this, userCombo, levelCombo, permissionDialog]() {
        QString userId = userCombo->currentText();
         UserRole level = static_cast<UserRole>(levelCombo->currentData().toInt());
        
         if (m_permissionManager->setUserPermissions(userId, m_permissionManager->getRolePermissions(level))) {
            QMessageBox::information(permissionDialog, tr("Success"), 
                                   tr("Permission updated successfully for user: %1").arg(userId));
        } else {
            QMessageBox::warning(permissionDialog, tr("Error"), 
                               tr("Failed to update permission for user: %1").arg(userId));
        }
    });
    
    connect(closeButton, &QPushButton::clicked, permissionDialog, &QDialog::accept);
    
    permissionDialog->exec();
    delete permissionDialog;
}

void MainWindow::showExportDialog()
{
    if (!checkUserPermission(PERM_DATA_EXPORT)) {
        QMessageBox::warning(this, tr("Permission Denied"),
                           tr("You don't have permission to export data."));
        return;
    }
    
    // Create export configuration dialog
    QDialog *exportDialog = new QDialog(this);
    exportDialog->setWindowTitle(tr("Advanced Export"));
    exportDialog->setModal(true);
    exportDialog->resize(600, 400);
    
    QVBoxLayout *layout = new QVBoxLayout(exportDialog);
    
    // Format selection
    QHBoxLayout *formatLayout = new QHBoxLayout();
    QLabel *formatLabel = new QLabel(tr("Export Format:"), exportDialog);
    QComboBox *formatCombo = new QComboBox(exportDialog);
    formatCombo->addItems(m_dataExporter->getAvailableFormats());
    formatLayout->addWidget(formatLabel);
    formatLayout->addWidget(formatCombo);
    layout->addLayout(formatLayout);
    
    // File path selection
    QHBoxLayout *pathLayout = new QHBoxLayout();
    QLabel *pathLabel = new QLabel(tr("Output Path:"), exportDialog);
    QLineEdit *pathEdit = new QLineEdit(exportDialog);
    QPushButton *browseButton = new QPushButton(tr("Browse..."), exportDialog);
    pathLayout->addWidget(pathLabel);
    pathLayout->addWidget(pathEdit);
    pathLayout->addWidget(browseButton);
    layout->addLayout(pathLayout);
    
    // Connect browse button
    connect(browseButton, &QPushButton::clicked, [pathEdit, formatCombo]() {
        QString format = formatCombo->currentText().toLower();
        QString filter = QString("%1 Files (*.%2)").arg(format.toUpper(), format);
        QString fileName = QFileDialog::getSaveFileName(nullptr, tr("Save Export File"), 
                                                       QDir::homePath(), filter);
        if (!fileName.isEmpty()) {
            pathEdit->setText(fileName);
        }
    });
    
    // Dialog buttons
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *exportButton = new QPushButton(tr("Export"), exportDialog);
    QPushButton *cancelButton = new QPushButton(tr("Cancel"), exportDialog);
    buttonLayout->addStretch();
    buttonLayout->addWidget(exportButton);
    buttonLayout->addWidget(cancelButton);
    layout->addLayout(buttonLayout);
    
    connect(exportButton, &QPushButton::clicked, [this, pathEdit, formatCombo, exportDialog]() {
        if (pathEdit->text().isEmpty()) {
            QMessageBox::warning(exportDialog, tr("Warning"), tr("Please select an output path."));
            return;
        }
        
        // Configure export
        ExportConfig config;
        QString formatText = formatCombo->currentText().toLower();
        if (formatText == "csv") config.format = ExportFormat::CSV;
        else if (formatText == "json") config.format = ExportFormat::JSON;
        else if (formatText == "xml") config.format = ExportFormat::XML;
        else if (formatText == "pdf") config.format = ExportFormat::PDF;
        else if (formatText == "excel") config.format = ExportFormat::EXCEL;
        else if (formatText == "html") config.format = ExportFormat::HTML;
        else config.format = ExportFormat::CSV;
        
        config.outputPath = pathEdit->text();
        config.includeHeaders = true;
        
        // Perform export
        if (m_dataExporter->exportData(config)) {
            QMessageBox::information(exportDialog, tr("Success"), tr("Data exported successfully."));
            exportDialog->accept();
        } else {
            QMessageBox::critical(exportDialog, tr("Error"), tr("Export failed."));
        }
    });
    
    connect(cancelButton, &QPushButton::clicked, exportDialog, &QDialog::reject);
    
    exportDialog->exec();
    delete exportDialog;
}

void MainWindow::showPluginManager()
{
    if (!checkUserPermission(PERM_SYSTEM_CONFIG)) {
        QMessageBox::warning(this, tr("Permission Denied"),
                           tr("You don't have permission to manage plugins."));
        return;
    }
    
    // Create plugin manager dialog
    QDialog *pluginDialog = new QDialog(this);
    pluginDialog->setWindowTitle(tr("Plugin Manager"));
    pluginDialog->setModal(true);
    pluginDialog->resize(800, 600);
    
    QVBoxLayout *layout = new QVBoxLayout(pluginDialog);
    
    // Plugin list
    QTableWidget *pluginTable = new QTableWidget(pluginDialog);
    pluginTable->setColumnCount(4);
    QStringList headers;
    headers << tr("Name") << tr("Version") << tr("Status") << tr("Description");
    pluginTable->setHorizontalHeaderLabels(headers);
    
    // Load plugin information
    QList<PluginInfo> plugins = m_pluginSystem->getAvailablePlugins();
    pluginTable->setRowCount(plugins.size());
    
    for (int i = 0; i < plugins.size(); ++i) {
        const PluginInfo &plugin = plugins[i];
        pluginTable->setItem(i, 0, new QTableWidgetItem(plugin.name));
        pluginTable->setItem(i, 1, new QTableWidgetItem(plugin.version));
        pluginTable->setItem(i, 2, new QTableWidgetItem(plugin.loaded ? tr("Loaded") : tr("Not Loaded")));
        pluginTable->setItem(i, 3, new QTableWidgetItem(plugin.description));
    }
    
    layout->addWidget(pluginTable);
    
    // Plugin control buttons
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    QPushButton *loadButton = new QPushButton(tr("Load Plugin"), pluginDialog);
    QPushButton *unloadButton = new QPushButton(tr("Unload Plugin"), pluginDialog);
    QPushButton *refreshButton = new QPushButton(tr("Refresh"), pluginDialog);
    QPushButton *closeButton = new QPushButton(tr("Close"), pluginDialog);
    
    buttonLayout->addWidget(loadButton);
    buttonLayout->addWidget(unloadButton);
    buttonLayout->addWidget(refreshButton);
    buttonLayout->addStretch();
    buttonLayout->addWidget(closeButton);
    layout->addLayout(buttonLayout);
    
    // Connect plugin control buttons
    connect(refreshButton, &QPushButton::clicked, [this, pluginTable]() {
        m_pluginSystem->refreshPlugins();
        // Refresh table content
        QList<PluginInfo> plugins = m_pluginSystem->getAvailablePlugins();
        pluginTable->setRowCount(plugins.size());
        for (int i = 0; i < plugins.size(); ++i) {
            const PluginInfo &plugin = plugins[i];
            pluginTable->setItem(i, 0, new QTableWidgetItem(plugin.name));
            pluginTable->setItem(i, 1, new QTableWidgetItem(plugin.version));
            pluginTable->setItem(i, 2, new QTableWidgetItem(plugin.loaded ? tr("Loaded") : tr("Not Loaded")));
            pluginTable->setItem(i, 3, new QTableWidgetItem(plugin.description));
        }
    });
    
    connect(closeButton, &QPushButton::clicked, pluginDialog, &QDialog::accept);
    
    pluginDialog->exec();
    delete pluginDialog;
}

bool MainWindow::checkUserPermission(Permission permission)
{
    QString userId = m_userSession->getCurrentUser();
    return m_permissionManager->hasPermission(userId, permission);
}
